package frame.PayDetail;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.GoodMapper;
import org.example.mapper.PayDetailMapper;
import org.example.mapper.PayMainMapper;
import org.example.pojo.Good;
import org.example.pojo.PayDetail;
import org.example.pojo.PayMain;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class PayDetailAdd extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private SqlSession sqlSession = MyBatislianjian.getSqlSession();
    private PayDetailMapper payDetailMapper = sqlSession.getMapper(PayDetailMapper.class);
    private GoodMapper goodMapper = sqlSession.getMapper(GoodMapper.class);
    private PayMainMapper payMainMapper = sqlSession.getMapper(PayMainMapper.class);
    private JComboBox<String> gidComboBox;
    private JComboBox<Integer> pidComboBox;

    public PayDetailAdd() {
        // 设置内部窗口的标题和关闭方式
        setTitle("添加采购明细");
        setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        table = new JTable(tableModel);

        // 添加表头
        String[] columnNames = {"采购清单号", "商品编号", "采购数量", "商品单价", "商品总价", "备注"};
        tableModel.setColumnIdentifiers(columnNames);

        // 添加一行空白数据
        addEmptyRow();

        // 设置表格可编辑
        table.setEnabled(true);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        JScrollPane scrollPane = new JScrollPane(table);

        // 将表格添加到内部窗口的中心区域
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 初始化商品编号和采购清单号下拉框
        gidComboBox = new JComboBox<>();
        populateGidComboBox(); // 填充商品编号下拉框
        pidComboBox = new JComboBox<>();
        populatePidComboBox(); // 填充采购清单号下拉框

        // 将商品编号下拉框添加到表格的商品编号列
        TableColumn gidColumn = table.getColumnModel().getColumn(1); // 1是商品编号列的索引
        gidColumn.setCellEditor(new DefaultCellEditor(gidComboBox));

        // 将采购清单号下拉框添加到表格的采购清单号列
        TableColumn pidColumn = table.getColumnModel().getColumn(0); // 0是采购清单号列的索引
        pidColumn.setCellEditor(new DefaultCellEditor(pidComboBox));

        // 添加商品编号列编辑完成后的监听器
        tableModel.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                int row = e.getFirstRow();
                int column = e.getColumn();
                if (column == 1) { // 1是商品编号列的索引
                    updatePriceAndTotal(row);
                } else if (column == 2 || column == 3) { // 数量或单价变化
                    updateTotal(row);
                }
            }
        });

        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 提示用户确认添加
                int confirm = JOptionPane.showConfirmDialog(PayDetailAdd.this, "确认添加表格中的所有采购明细到数据库？", "确认", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    // 提取表格数据并添加到数据库
                    List<PayDetail> payDetailsToAdd = extractTableData();
                    if (payDetailsToAdd != null && !payDetailsToAdd.isEmpty()) {
                        boolean allValid = true;

                        for (PayDetail payDetail : payDetailsToAdd) {
                            // 检查关键字段不能为空
                            if (payDetail.getPid() == null || payDetail.getGid().isEmpty() || payDetail.getPcount() == null || payDetail.getGpay() == 0.0f || payDetail.getTotal() == 0.0f) {
                                allValid = false;
                                break;
                            }
                        }

                        if (allValid) {
                            try {
                                // 批量添加采购明细到数据库
                                for (PayDetail payDetail : payDetailsToAdd) {
                                    payDetailMapper.addPayDetail(payDetail);
                                }
                                sqlSession.commit(); // 提交事务

                                // 清空表格数据
                                tableModel.setRowCount(0);
                                addEmptyRow(); // 添加新的空行
                                JOptionPane.showMessageDialog(PayDetailAdd.this, "成功添加 " + payDetailsToAdd.size() + " 条采购明细到数据库！", "提示", JOptionPane.INFORMATION_MESSAGE);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                                JOptionPane.showMessageDialog(PayDetailAdd.this, "添加采购明细时出现错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                            }
                        } else {
                            JOptionPane.showMessageDialog(PayDetailAdd.this, "每一行的采购清单号、商品编号、采购数量、商品单价、商品总价都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(PayDetailAdd.this, "表格中没有数据可以添加！", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }
        });

        // 添加手动添加明细行按钮
        JButton manualAddButton = new JButton("添加采购明细行");
        manualAddButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 添加新的空白行
                addEmptyRow();
            }
        });

        // 返回按钮
        JButton returnButton = new JButton("返回");
        returnButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new PayDetailPanel());
            }
        });

        // 将按钮添加到内部窗口的南部区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(addButton);
        buttonPanel.add(manualAddButton);
        buttonPanel.add(returnButton);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        // 设置内部窗口的大小和可见性
        setSize(800, 600);
        setVisible(true);
    }

    // 添加空白行到表格中
    private void addEmptyRow() {
        tableModel.addRow(new Object[]{"", "", "", "", "", ""});
    }

    // 提取表格数据的方法
    public List<PayDetail> extractTableData() {
        List<PayDetail> payDetails = new ArrayList<>();
        for (int row = 0; row < table.getRowCount(); row++) {
            Integer pid = null;
            try {
                // 尝试从表格中获取采购清单号，并进行类型转换
                if (table.getValueAt(row, 0) instanceof Integer) {
                    pid = (Integer) table.getValueAt(row, 0);
                } else if (table.getValueAt(row, 0) instanceof String) {
                    String pidStr = (String) table.getValueAt(row, 0);
                    if (!pidStr.isEmpty()) {
                        pid = Integer.parseInt(pidStr);
                    }
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(PayDetailAdd.this, "采购清单号字段必须是整数！", "错误", JOptionPane.ERROR_MESSAGE);
                return null; // 或者其他处理逻辑
            }

            String gid = (String) table.getValueAt(row, 1); // 商品编号
            Integer pcount = null;
            Float gPay = null;
            Float total = null;
            String other = (String) table.getValueAt(row, 5); // 备注

            try {
                if (table.getValueAt(row, 2) instanceof String) {
                    String pcountStr = (String) table.getValueAt(row, 2);
                    if (!pcountStr.isEmpty()) {
                        pcount = Integer.parseInt(pcountStr);
                    }
                } else if (table.getValueAt(row, 2) instanceof Integer) {
                    pcount = (Integer) table.getValueAt(row, 2);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(PayDetailAdd.this, "采购数量字段必须是整数！", "错误", JOptionPane.ERROR_MESSAGE);
                return null;
            }

            try {
                if (table.getValueAt(row, 3) instanceof String) {
                    String gPayStr = (String) table.getValueAt(row, 3);
                    if (!gPayStr.isEmpty()) {
                        gPay = Float.parseFloat(gPayStr);
                    }
                } else if (table.getValueAt(row, 3) instanceof Float) {
                    gPay = (Float) table.getValueAt(row, 3);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(PayDetailAdd.this, "商品单价字段必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
                return null;
            }

            try {
                if (table.getValueAt(row, 4) instanceof String) {
                    String totalStr = (String) table.getValueAt(row, 4);
                    if (!totalStr.isEmpty()) {
                        total = Float.parseFloat(totalStr);
                    }
                } else if (table.getValueAt(row, 4) instanceof Float) {
                    total = (Float) table.getValueAt(row, 4);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(PayDetailAdd.this, "商品总价字段必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
                return null;
            }

            // 创建 PayDetail 对象并添加到列表
            PayDetail payDetail = new PayDetail(pid, gid, pcount, gPay, total, other);
            payDetails.add(payDetail);
        }
        return payDetails;
    }

    // 更新商品单价和商品总价
    private void updatePriceAndTotal(int row) {
        // 获取商品编号
        String gid = (String) table.getValueAt(row, 1);

        // 根据商品编号查询商品信息
        Good good = goodMapper.selectGoodById(gid);

        // 更新商品单价
        if (good != null) {
            table.setValueAt(good.getGPay(), row, 3); // 3是商品单价列的索引
            updateTotal(row); // 更新商品总价
        } else {
            JOptionPane.showMessageDialog(this, "找不到编号为 " + gid + " 的商品信息！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    // 更新商品总价
    private void updateTotal(int row) {
        // 获取采购数量和商品单价
        Integer pcount = null;
        Float gPay = null;

        Object pcountValue = table.getValueAt(row, 2);
        Object gPayValue = table.getValueAt(row, 3);

        // 检查并转换采购数量
        if (pcountValue instanceof Integer) {
            pcount = (Integer) pcountValue;
        } else if (pcountValue instanceof String) {
            try {
                pcount = Integer.parseInt((String) pcountValue);
            } catch (NumberFormatException e) {
                // Handle parsing error or notify user
                return;
            }
        }

        // 检查并转换商品单价
        if (gPayValue instanceof Float) {
            gPay = (Float) gPayValue;
        } else if (gPayValue instanceof String) {
            try {
                gPay = Float.parseFloat((String) gPayValue);
            } catch (NumberFormatException e) {
                // Handle parsing error or notify user
                JOptionPane.showMessageDialog(this, "商品单价必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }

        // 计算商品总价并更新表格
        if (pcount != null && gPay != null) {
            Float total = pcount * gPay;
            table.setValueAt(total, row, 4); // 4是商品总价列的索引
        }
    }


    // 填充商品编号下拉框
    private void populateGidComboBox() {
        List<Good> goods = goodMapper.selectAll();
        for (Good good : goods) {
            gidComboBox.addItem(good.getGid());
        }
    }

    // 填充采购清单号下拉框
    private void populatePidComboBox() {
        List<PayMain> payMains = payMainMapper.selectAll();
        for (PayMain payMain : payMains) {
            pidComboBox.addItem(payMain.getPid());
        }
    }
}
